//
//  UserAccountViewModel.m
//  OCMicroBlog
//
//  Created by 002 on 15/11/5.
//  Copyright © 2015年 002. All rights reserved.
//

#import "UserAccountViewModel.h"
#import "NetworkTools.h"

@interface UserAccountViewModel ()

@end

@implementation UserAccountViewModel

/**
 *  构造函数
 *
 *  @return UserAccountViewModel
 */
static UserAccountViewModel *_instance;

#pragma mark - 单例处理
/**
 *  单例接口 避免在沙盒中重复加载 ‘归档’ 文件，提高效率
 *
 *  @return UserAccountViewModel
 */
+ (instancetype)sharedAccountViewModel {
    
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
        _instance.userAccount = [NSKeyedUnarchiver unarchiveObjectWithFile:[_instance accountPath]];
        // 如果帐号已经过期，清空帐号，要求用户重新登录
        if ([_instance isExpired]) {
            _instance.userAccount = nil;
        }
    });
    
    return _instance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t audio;
    NSLog(@"audio=%ld,地址：%p",audio,&audio);
    dispatch_once(&audio, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

- (id)copy
{
    return _instance;
}

+ (id)copyWithZone:(struct _NSZone *)zone
{
    return _instance;
}

#pragma mark - 网络请求方法
/**
 *  加载 AccessToken
 *
 *  @param code        授权码
 *  @param isSuccessed 是否成功回调
 */
- (void)loadAccessTokenWithCode:(NSString *)code finished:(finishedCallBack)finished {
    [[NetworkTools sharedTools] loadAccessTokenWithCode:code finished:^(id result, NSError *error) {
        
        // 1.) 判断错误
        if (error) {
            
            NSLog(@"错误：%@",error);
            return;
        }
        
        NSLog(@"成功回调%@",result);
        
        // 2.) 创建用户账户
        UserAccount *userAccount = [UserAccount initWithDict:result];
        self.userAccount = userAccount;
        NSLog(@"userAccount=%@",userAccount.description);
        
        // 3.）加载用户信息
        [self loadUserInfo:self.userAccount finished:finished];
        
    }];
}

/**
 *  加载用户信息
 *
 *  @param userAccount 用户账户
 *  @param finished    完成回调
 */
- (void)loadUserInfo:(UserAccount *)userAccount finished:(finishedCallBack)finished {
    
    [[NetworkTools sharedTools] loadUserInfoWithUID:userAccount.uid finished:^(id result, NSError *error) {
        
        // 1. 判断是否出错
        if (error) {
            NSLog(@"出错%@",error);
            return;
        }
        
        // 2. 判断返回是否为空
        NSDictionary *dict = (NSDictionary *)result;
        if (!dict) {
            NSLog(@"返回为空:%@",result);
            return;
        }
        
        // 3. 设置模型数据
        self.userAccount.screen_name = dict[@"screen_name"];
        self.userAccount.avatar_large = dict[@"avatar_large"];
        
        NSLog(@"%@",self.userAccount);
        
        [self.userAccount saveUserAccount];
        
        // 4. 完成回调
        finished(true);
    }];
}

#pragma mark - 属性设置
/**
 *  解档文件路径
 *
 *  @return 解档路径
 */
- (NSString *)accountPath {
    
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true)[0];
    
    return [path stringByAppendingPathComponent:@"account.plist"];
}

/**
 *  是否过期
 *
 *  @return
 */
- (BOOL)isExpired {
    
    if ([self.userAccount.expiresDate compare:[NSDate date]] == NSOrderedDescending) {
        
        return false;
    }
    return true;
}

/**
 *  是否登录标记  
 *
 *  @return
 */
- (BOOL)userLogin {

    // 有access_token且不为空、未过期
    return (self.userAccount.access_token) && !self.isExpired;
//    return false;
}

/**
 *  token 字典
 *
 *  @return token 字典
 */
- (NSMutableDictionary *)tokenDict {
    if (!_tokenDict) {
        _tokenDict = [NSMutableDictionary  dictionary];
    }
    if (self.userAccount.access_token) {
        [_tokenDict setObject:self.userAccount.access_token forKey:@"access_token"];
    }
    return _tokenDict;
}

- (NSURL *)avatarUrl {
    return [[NSURL alloc] initWithString:(self.userAccount.avatar_large == nil ? @"" : self.userAccount.avatar_large)];
}

@end
